﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Common;
using DevExpress.XtraEditors;

namespace TaxiDispatchClient
{
    public partial class PhoneMonitorForm : DevExpress.XtraEditors.XtraForm
    {
        public PhoneMonitorForm()
        {
            InitializeComponent();
        }

        public PhoneMonitorForm(string phoneNumber)
        {
            InitializeComponent();
            textEdit_phoneNumber.Text = "9" + phoneNumber;
            _phoneNumber = phoneNumber;
            label_notice.Text = "";
            SetPortNameValues();
        }

        private string _phoneNumber;

        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion

        private void simpleButton_call_Click(object sender, EventArgs e)
        {
            if (_phoneNumber != "")
            {
                simpleButton_call.Enabled = false;
                textEdit_phoneNumber.Enabled = false;
                label_notice.Text = "正在发送监听命令...";
                if (SendData(ConstParameters.CmdTaxiMonitor, new byte[1], _phoneNumber))
                {
                    label_notice.Text = "开始拨号...";
                    if(MainForm.PhoneModem.Monitor(_phoneNumber))
                    {
                        label_notice.Text = "开始监听...";
                    }
                    else
                    {
                        label_notice.Text = "监听失败，设备故障!";
                        simpleButton_call.Enabled = true;
                        textEdit_phoneNumber.Enabled = true;
                    }
                }
                else
                {
                    label_notice.Text = "监听命令无响应，请重试！";
                    simpleButton_call.Enabled = true;
                    textEdit_phoneNumber.Enabled = true;
                }
            }
        }

        private bool SendData(ushort messageId, byte[] messageBody, string phoneNum)
        {
            try
            {
                string transferServerIp = OperateConfig.GetClientTransferServerIp();
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipAddress = IPAddress.Parse(transferServerIp);
                IPEndPoint address = new IPEndPoint(ipAddress, ConstParameters.TransferListenPort);
                socket.Connect(address);
                socket.NoDelay = true;
                List<byte> mBytes = new List<byte>();

                mBytes.AddRange(BitConverter.GetBytes(messageId).Reverse());
                mBytes.AddRange(CommonRoutine.BcdStringToBytes(phoneNum.PadLeft(12, '0')));
                IPAddress localIp = ((IPEndPoint)(socket.LocalEndPoint)).Address;
                mBytes.AddRange(localIp.GetAddressBytes());
                mBytes.AddRange(messageBody);
                byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdRetweetTaxiDispatchClient, false, false, mBytes.ToArray().Length, new byte[6], new byte[2], 0, 0);
                byte[] sendData = OperateAgreement.PackageSendData(messageHead, mBytes.ToArray());
                socket.Send(sendData);
                Thread.Sleep(100);
                socket.ReceiveTimeout = 5000;

                byte[] receData = new byte[100];
                int receDatacount = socket.Receive(receData);

                if (receDatacount >= ConstParameters.MhLenth)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                return false;
            }

        }

        private void simpleButton_break_Click(object sender, EventArgs e)
        {
            MainForm.PhoneModem.HangUp();
            simpleButton_call.Enabled = true;
            textEdit_phoneNumber.Enabled = true;
            label_notice.Text = "";
        }

        private void SetPortNameValues()
        {
            comboBoxEdit_Comlist.Properties.Items.Clear();
            foreach (string str in SerialPort.GetPortNames())
            {
                comboBoxEdit_Comlist.Properties.Items.Add(str);
            }
            if (comboBoxEdit_Comlist.Properties.Items.Count > 0)
            {
                comboBoxEdit_Comlist.SelectedItem = Service.PhoneModemCom.serialPort.PortName;
            }
            else
            {
                comboBoxEdit_Comlist.Enabled = false;
                simpleButton_modify.Enabled = false;
                simpleButton_call.Enabled = false;
                lb_noComs.Visible = true;
            }
        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (simpleButton_modify.Text == "更改")
            {
                comboBoxEdit_Comlist.Enabled = true;
                simpleButton_modify.Text = "保存";
                simpleButton_cancel.Visible = true;
            }
            else
            {
                string newCom = comboBoxEdit_Comlist.Properties.Items[comboBoxEdit_Comlist.SelectedIndex].ToString();
                if (MainForm.PhoneModem.ChangeCom(newCom))
                {
                    comboBoxEdit_Comlist.Enabled = false;
                    simpleButton_modify.Text = "更改";
                    simpleButton_cancel.Visible = false;
                }
                else
                {
                    XtraMessageBox.Show("更改失败！");
                }
            }
        }

        private void simpleButton_cancel_Click(object sender, EventArgs e)
        {
            comboBoxEdit_Comlist.SelectedItem = Service.PhoneModemCom.serialPort.PortName;
            comboBoxEdit_Comlist.Enabled = false;
            simpleButton_modify.Text = "更改";
            simpleButton_cancel.Visible = false;

        }
    }
}